package hy.planegame.sprite

import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.RectF
import hy.planegame.R
import hy.planegame.utils.context
import hy.planegame.utils.paint
import hy.planegame.utils.screenHeight
import hy.planegame.utils.screenWidth

/**
 * Created time : 2017/8/31 16:54.
 * @author HY
 */
class Player : Sprite<Player>() {
    private var health: Int = 1000
    private var count = 3 //数量

    private val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.icon_player)

    private val width = bitmap.width
    private val height = bitmap.height

    private val playerBoom = PlayerBoom()
    private var centerX = screenWidth / 2
    private var centerY = screenHeight - height / 2 - 50
    private var isBoom = false
    private val rectF = RectF()

    private var num = 0

    override fun draw(canvas: Canvas?) {
        canvas ?: return
        if (isBoom) {//爆炸
            playerBoom.start(centerX, centerY)
            playerBoom.draw(canvas)
        } else {
            rectF.set(
                    centerX - width / 2f,
                    centerY - height / 2f,
                    centerX + width / 2f,
                    centerY + height / 2f
            )
            canvas.drawBitmap(bitmap, null, rectF, paint)
        }
    }

    fun moveTo(centerX: Int, centerY: Int) {
        if (centerX >= width / 2 && centerX < screenWidth - width / 2
                && centerY >= height / 2 && centerY <= screenHeight - height / 2) {
            this.centerX = centerX
            this.centerY = centerY
        }
    }

    fun isInRange(x: Int, y: Int) =
            x >= centerX - width / 2 && x <= centerX + width / 2 && y >= centerY - height / 2 && y <= centerY + height / 2


    override fun logic() {
        if (isBoom) {
            playerBoom.logic()

        } else {
            if (num % 10 == 0) {
                val bullet = Bullet(centerX, centerY - height / 2)
                bullet.onDestroy {
                    _onBulletDestroy?.invoke(bullet)
                }

                _onAdd?.invoke(bullet)
            }
            num++
        }
    }

    private var _onBulletDestroy: ((bull: Bullet) -> Unit)? = null

    fun onBulletDestroy(callback: (bull: Bullet) -> Unit) {
        _onBulletDestroy = callback
    }


    private var _onAdd: ((bull: Bullet) -> Unit)? = null
    fun addBullet(callback: (bull: Bullet) -> Unit) {
        _onAdd = callback
    }

    override fun destroy() {
        rectF.setEmpty()
        num = 0
    }
}